<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="商家名称" prop="merchantId">
        <el-select 
          v-model="queryParams.merchantId"
          placeholder="请选择商家" 
          filterable 
          :loading="merchantLoading"
          class="!w-240px"
          popper-class="account-select-dropdown"
          clearable
          @focus="handleSelectFocus"
          @visible-change="handleVisibleChange"
          @filter-method="handleSearch"
        >
          <el-option
            v-for="item in merchantList"
            :key="item.id"
            :label="item.merchantName"
            :value="item.id"
          />
          <template #dropdown>
            <div class="merchant-select-content">
              <div v-if="merchantList.length === 0" class="merchant-empty">
                <el-empty description="暂无数据" />
              </div>
              <div v-if="hasMore && !merchantLoading" class="merchant-loading">
                <el-icon class="is-loading"><Loading /></el-icon>
                <span class="loading-text">加载更多...</span>
              </div>
            </div>
          </template>
        </el-select>
      </el-form-item>
   
      <el-form-item label="账户类型" prop="accountType">
        <el-select
          v-model="queryParams.accountType"
          placeholder="请选择账户类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.JULIANG_ACCOUNT_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
     
     
      <el-form-item label="退款日期" prop="transactionDate">
        <el-date-picker
          v-model="queryParams.transactionDate"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="交易流水号" prop="transactionNo">
        <el-input
          v-model="queryParams.transactionNo"
          placeholder="请输入交易流水号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="退款状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择记录状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.JULIANG_RECORD_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
     
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['juliang:fund-record:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['juliang:fund-record:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="商家名称" align="center" prop="merchantName" />
      <el-table-column label="交易类型" align="center" prop="recordType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.JULIANG_RECORD_TYPE" :value="scope.row.recordType" />
        </template>
      </el-table-column>
      <el-table-column label="交易流水号" align="center" prop="transactionNo" min-width="120px" />
      <!-- <el-table-column
label="充值日期" align="center" prop="transactionDate"  :formatter="dateFormatter"
      width="180px"/> -->

      
      <el-table-column label="退款状态" align="center" prop="status" :width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.JULIANG_RECORD_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="账户类型" align="center" prop="accountType"  :width="100"> 
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.JULIANG_ACCOUNT_TYPE" :value="scope.row.accountType" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="账户ID" align="center" prop="accountId" /> -->
      <el-table-column label="金额" align="center" prop="amount" />
      <el-table-column label="收款名称" align="center" prop="payeeName" min-width="120px" />
      <el-table-column label="收款账号" align="center" prop="payeeAccount" min-width="120px" />
      <el-table-column label="收款开户行" align="center" prop="payeeBank" min-width="120px" />
      <!-- <el-table-column
label="审核日期" align="center" prop="auditDate"  :formatter="dateFormatter"
      width="180px"/> -->
      <el-table-column label="拒绝理由" align="center" prop="rejectReason" />
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />

      <el-table-column label="操作" align="center" min-width="150px" fixed="right">
        <template #default="scope">
          <!-- 隐藏编辑按钮 -->
          <!--
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['juliang:fund-record:update']"
            :disabled="scope.row.status === 1"
          >
            编辑
          </el-button>
          -->

          <!-- 仅待审核（status === 0）时显示“通过”按钮 -->
          <el-button
            v-if="scope.row.status === 0"
            link
            type="success"
            v-hasPermi="['juliang:fund-record:update']"
            @click="handleApprove(scope.row)"
          >
            通过
          </el-button>
          <!-- 仅待审核（status === 0）时显示“拒绝”按钮 -->
          <el-button
            v-if="scope.row.status === 0"
            link
            type="danger"
            v-hasPermi="['juliang:fund-record:update']"
            @click="openRejectDialog(scope.row)"
          >
            拒绝
          </el-button>
          
          <!-- 隐藏删除按钮 -->
          <!--
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['juliang:fund-record:delete']"
            :disabled="scope.row.status === 1"
          >
            删除
          </el-button>
          -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <FundRecordForm ref="formRef" @success="getList" />

  <!-- 拒绝弹窗 -->
  <Dialog :title="'拒绝记录'" v-model="rejectDialogVisible">
    <div class="record-info">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商家名称">{{ rejectForm.merchantName }}</el-descriptions-item>
        <el-descriptions-item label="交易流水号">{{ rejectForm.transactionNo }}</el-descriptions-item>
        <el-descriptions-item label="金额">{{ rejectForm.amount }}</el-descriptions-item>
        <el-descriptions-item label="收款名称">{{ rejectForm.payeeName }}</el-descriptions-item>
      </el-descriptions>
    </div>
    <el-form
      ref="rejectFormRef"
      :model="rejectForm"
      :rules="rejectRules"
      label-width="100px"
      class="mt-4"
    >
      <el-form-item label="拒绝理由" prop="rejectReason">
        <el-input
          v-model="rejectForm.rejectReason"
          type="textarea"
          placeholder="请输入拒绝理由"
          :rows="4"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="rejectDialogVisible = false">取 消</el-button>
      <el-button type="danger" @click="handleReject" :loading="rejectLoading">确认拒绝</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, getBoolDictOptions, DICT_TYPE } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { FundRecordApi, FundRecordVO } from '@/api/juliang/fundrecord'
import { MerchantApi, MerchantVO } from '@/api/juliang/merchant'
import { Loading } from '@element-plus/icons-vue'
import { throttle, debounce } from 'lodash-es'
import FundRecordForm from './FundRecordForm.vue'

import { createImageViewer } from '@/components/ImageViewer'
import { useRoute } from 'vue-router'


/** 商品图预览 */
const imagePreview = (imgUrl: string) => {
  createImageViewer({
    urlList: [imgUrl]
  })
}

    
/** 资金记录 列表 */
defineOptions({ name: 'FundRecord' })

const message = useMessage() // 消息弹窗

const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<FundRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const merchantList = ref<MerchantVO[]>([]) // 商家列表
const merchantLoading = ref(false) // 商家列表加载状态
const hasMore = ref(true) // 是否还有更多数据
const loadingNewPage = ref(false) // 标记是否正在加载新页面
const searchKeyword = ref('') // 搜索关键字

const merchantQuery = reactive({
  pageNo: 1,
  pageSize: 10,
  merchantName: undefined as string | undefined
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  recordNo: undefined,
  merchantId: undefined,
  recordType: 2,
  accountType: undefined,
  accountId: undefined,
  amount: undefined,
  payerName: undefined,
  payerAccount: undefined,
  payerBank: undefined,
  payeeName: undefined,
  payeeAccount: undefined,
  payeeBank: undefined,
  transactionDate: [],
  transactionNo: undefined,
  status: undefined as number | undefined,
  createTime: [],
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 获取商家列表 */
const getMerchantList = async (isLoadMore = false) => {
  if (merchantLoading.value || (isLoadMore && !hasMore.value)) return
  
  if (isLoadMore) {
    loadingNewPage.value = true
  } else {
    merchantLoading.value = true
  }

  try {
    const data = await MerchantApi.getMerchantPage({
      pageNo: merchantQuery.pageNo,
      pageSize: merchantQuery.pageSize,
      merchantName: searchKeyword.value
    })
    
    if (data?.list?.length > 0) {
      merchantList.value = isLoadMore 
        ? [...merchantList.value, ...data.list]
        : data.list
      hasMore.value = data.list.length === merchantQuery.pageSize
    } else {
      if (!isLoadMore) {
        merchantList.value = []
      }
      hasMore.value = false
    }
  } catch (error) {
    console.error('获取商家列表失败:', error)
    message.error('获取商家列表失败')
    if (!isLoadMore) {
      merchantList.value = []
    }
  } finally {
    merchantLoading.value = false
    loadingNewPage.value = false
  }
}

/** 监听下拉框滚动 */
const handleDropdownScroll = throttle(async (e: Event) => {
  const target = e.target as HTMLElement
  const { scrollTop, scrollHeight, clientHeight } = target
  
  // 距离底部50px时预加载下一页
  if (scrollHeight - scrollTop - clientHeight < 50 && hasMore.value && !loadingNewPage.value) {
    merchantQuery.pageNo++
    await getMerchantList(true)
  }
}, 200)

/** 处理下拉框显示状态变化 */
const handleVisibleChange = (visible: boolean) => {
  if (visible) {
    // 下拉框显示时，添加滚动监听
    nextTick(() => {
      const dropdownWrapper = document.querySelector('.account-select-dropdown .el-select-dropdown__wrap')
      if (dropdownWrapper) {
        dropdownWrapper.addEventListener('scroll', handleDropdownScroll)
      }
    })
  } else {
    // 下拉框隐藏时，移除滚动监听
    const dropdownWrapper = document.querySelector('.account-select-dropdown .el-select-dropdown__wrap')
    if (dropdownWrapper) {
      dropdownWrapper.removeEventListener('scroll', handleDropdownScroll)
    }
  }
}

/** 处理搜索 */
const handleSearch = debounce((query: string) => {
  searchKeyword.value = query.trim()
  merchantQuery.pageNo = 1
  hasMore.value = true
  merchantList.value = []
  getMerchantList()
}, 300)

/** 处理下拉框获得焦点 */
const handleSelectFocus = () => {
  if (merchantList.value.length === 0) {
    searchKeyword.value = ''
    merchantQuery.pageNo = 1
    hasMore.value = true
    getMerchantList()
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 确保 recordType 始终为 2 (退款记录)
    const params = {
      ...queryParams,
    }
    console.log('退款记录查询参数:', params)
    const data = await FundRecordApi.getFundRecordPage(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryParams.recordNo = undefined
  queryParams.merchantId = undefined
  queryParams.recordType = 2
  queryParams.accountType = undefined
  queryParams.accountId = undefined
  queryParams.amount = undefined
  queryParams.payerName = undefined
  queryParams.payerAccount = undefined
  queryParams.payerBank = undefined
  queryParams.payeeName = undefined
  queryParams.payeeAccount = undefined
  queryParams.payeeBank = undefined
  queryParams.transactionDate = []
  queryParams.transactionNo = undefined
  queryParams.status = undefined
  queryParams.createTime = []
  // 重置商家相关的状态
  merchantList.value = []
  hasMore.value = true
  merchantQuery.pageNo = 1
  searchKeyword.value = ''
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.confirm('是否确认删除编号为"' + id + '"的数据项?')
    // 发起删除
    await FundRecordApi.deleteFundRecordById(id)
    message.success(t('common.deleteSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 修改状态 */
const handleStatusChange = async (row: FundRecordVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要' + text + '记录吗?')
    // 发起修改状态
    await FundRecordApi.updateFundRecordStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch (e){
    console.log(e)
    // 取消后，进行恢复按钮
    row.status =
        row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 发起导出
    const data = await FundRecordApi.exportFundRecord({
      ...queryParams,
    })
    download.excel(data, '退款记录.xls')
  } catch {}
}

/** 拒绝弹窗 */
const rejectDialogVisible = ref(false)
const rejectLoading = ref(false)
const rejectFormRef = ref()
const rejectForm = reactive({
  id: undefined as number | undefined,
  merchantName: '',
  transactionNo: '',
  amount: '',
  payeeName: '',
  rejectReason: ''
})

const rejectRules = reactive({
  rejectReason: [{ required: true, message: '请输入拒绝理由', trigger: 'blur' }]
})

/** 处理通过 */
const handleApprove = async (row: FundRecordVO) => {
  try {
    // 通过的二次确认
    await message.confirm(`确认通过商家"${row.merchantName}"的退款申请吗？`)
    // 发起通过请求
    await FundRecordApi.auditRecord(row.id, 1, '')
    message.success('通过成功')
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('通过失败:', error)
  }
}

/** 打开拒绝弹窗 */
const openRejectDialog = (row: FundRecordVO) => {
  rejectForm.id = row.id
  rejectForm.merchantName = row.merchantName || ''
  rejectForm.transactionNo = row.transactionNo || ''
  rejectForm.amount = row.amount?.toString() || ''
  rejectForm.payeeName = row.payeeName || ''
  rejectForm.rejectReason = ''
  rejectDialogVisible.value = true
}

/** 处理拒绝 */
const handleReject = async () => {
  try {
    // 校验表单
    await rejectFormRef.value.validate()
    // 提交请求
    rejectLoading.value = true
    
    let res = await FundRecordApi.auditRecord(
      rejectForm.id!,
      2,
      rejectForm.rejectReason
    )
    
    if(res.code == 0){
      message.success('拒绝成功')
      rejectDialogVisible.value = false
      // 刷新列表
      await getList()
    }else{
      message.error(res.msg)
      rejectDialogVisible.value = true
    }
  } catch (error) {
  } finally {
    rejectLoading.value = false
  }
}

/** 初始化 **/
const route = useRoute()
onMounted(() => {
  // 接收页面跳转传过来的 status 参数
  const statusParam = route.query.status
  if (statusParam !== undefined && statusParam !== null && statusParam !== '') {
    const statusValue = Array.isArray(statusParam) ? statusParam[0] : statusParam
    queryParams.status = Number(statusValue)
  }
  getList()
})
</script>

<style lang="scss" scoped>
.merchant-select-content {
  .merchant-empty {
    padding: 20px;
    text-align: center;
  }
  
  .merchant-loading {
    padding: 8px 0;
    text-align: center;
    background-color: var(--el-bg-color);
    border-top: 1px solid var(--el-border-color-lighter);
    
    .el-icon {
      margin-right: 6px;
      font-size: 16px;
      color: var(--el-color-primary);
      vertical-align: middle;
    }
    
    .loading-text {
      font-size: 13px;
      color: var(--el-text-color-secondary);
      vertical-align: middle;
    }
  }
}

:deep(.el-select-dropdown__wrap) {
  max-height: 300px;
}

:deep(.el-select-dropdown__list) {
  padding: 0;
}
</style>